package com.example.yichuangyun.mvvm.ui.activity.order;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityOrderListBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.TimePicker;
import com.example.yichuangyun.dialog.TreeDialog;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.LabelModel;
import com.example.yichuangyun.model.order.OrderListDataModel;
import com.example.yichuangyun.model.order.OrderListParamsModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.CompanyDetailsActivity;
import com.example.yichuangyun.mvvm.ui.activity.order.view.OrderListViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.OrderLabelAdapter;
import com.example.yichuangyun.mvvm.ui.adapter.OrderListAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DateUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.UMengUtil;
import com.example.yichuangyun.utils.treelist.Node;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单列表
 */
public class OrderListActivity extends BaseActivity<ActivityOrderListBinding, OrderListViewModel> implements OrderLabelAdapter.OnLabelItemClickListener {

    private OrderListParamsModel orderListParamsModel;
    private int page = 1;
    private OrderListAdapter adapter;
    private final List<LabelModel> orderStatusData = new ArrayList<>();
    private final List<LabelModel> orderTypeData = new ArrayList<>();
    private final List<LabelModel> paymentData = new ArrayList<>();
    private final List<LabelModel> workTypeData = new ArrayList<>();
    private OrderLabelAdapter orderStatusAdapter, orderTypeAdapter, paymentAdapter, workTypeAdapter;
    private String orderText;
    private TimePicker timePicker;
    private MyDialog myDialog;
    private boolean isStart;
    private TreeDialog treeDialog;
    private final List<Node> mTreeData = new ArrayList<>();
    private boolean isSignPerson;
    private String mKeyword = "";
    private String mTelNumber;
    private String businessId;
    private String clientName;
    /**
     * 0电话拨打、1款项确认
     */
    private int flag;
    private String orderId;
    private OrderListDataModel.OrderRecordsModel orderRecordsModel;
    private int mPosition;

    private Node chooseNode;

    @Override
    protected OrderListViewModel bindModel() {
        return getViewModel(this, OrderListViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        UMengUtil.setCountEventId(Constant.ORDER_LIST);
        binding.includeSelect.recyclerViewOrderStatus.setLayoutManager(new GridLayoutManager(context, 3));
        binding.includeSelect.recyclerViewOrderType.setLayoutManager(new GridLayoutManager(context, 3));
        binding.includeSelect.recyclerViewPayment.setLayoutManager(new GridLayoutManager(context, 3));
        binding.includeSelect.recyclerViewWorkType.setLayoutManager(new GridLayoutManager(context, 3));
        initSelectData();
        binding.includeTop.llBack.setVisibility(View.VISIBLE);
        binding.includeTop.ivAddBusiness.setVisibility(View.GONE);
        binding.includeTop.ivSort.setVisibility(View.GONE);
        binding.includeTop.tvTitleText.setText(getString(R.string.order_text));
        orderText = getString(R.string.all_order_text);
        binding.includeTop.tvBusinessCount.setText(getString(R.string.all_order_count, orderText, 0));
        adapter = new OrderListAdapter(context);
        binding.recyclerView.setAdapter(adapter);
        adapter.setEmptyViewEnable(true);
        adapter.setEmptyViewLayout(context, R.layout.loading_view);
        orderListParamsModel = new OrderListParamsModel();
        getOrderList(page);
        initDialog();
        initTreeDialog();
        viewModel.getTreeList("");
    }

    private void getOrderList(int page) {
        orderListParamsModel.setCurrent(page);
        viewModel.getOrderList(orderListParamsModel);
    }

    @Override
    protected void initClick() {
        viewModel.onDelayClick(binding.includeTop.llBack, o -> finish());

        viewModel.data.observe(this, orderListDataModel -> {
            if (orderListDataModel != null) {
                binding.includeTop.tvBusinessCount.setText(getString(R.string.all_order_count, orderText, orderListDataModel.getCount()));
                if (null != orderListDataModel.getRecords()) {
                    if (orderListDataModel.getRecords().size() < Constant.pageSize) {
                        binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
                if (page == 1) {
                    if (null == orderListDataModel.getRecords() || orderListDataModel.getRecords().isEmpty()) {
                        adapter.setEmptyViewLayout(context, R.layout.layout_empty_list);
                    }
                    binding.smartRefreshLayout.resetNoMoreData();
                    adapter.submitList(orderListDataModel.getRecords());
                    binding.smartRefreshLayout.finishRefresh();
                } else {
                    adapter.addAll(orderListDataModel.getRecords());
                    binding.smartRefreshLayout.finishLoadMore();
                }
            }
        });

        viewModel.treeData.observe(this, setShareBean -> {
            dismissLoadingDialog();
            if (setShareBean.getData() != null) {
                Node node = setShareBean.getData();
                mTreeData.add(new Node(node.getName(), node.getId(), node.getParentId(), node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
                initList(node.getChildren());
                initList(node.getUserList());
                if (chooseNode != null) {
                    for (Node mNode : mTreeData) {
                        if (mNode.getId().equals(chooseNode.getId())) {
                            mNode.setChecked(true);
                            break;
                        }
                    }
                }
            }
            treeDialog.refreshData(TextUtils.isEmpty(mKeyword) ? 1 : 10);
        });

        viewModel.mErrorData.observe(this, s -> {
            dismissLoadingDialog();
            binding.smartRefreshLayout.finishRefresh();
            binding.smartRefreshLayout.finishLoadMore();
        });

        viewModel.confirmSuccessData.observe(this, s -> {
            dismissLoadingDialog();
            ToastHelper.show(getString(R.string.confirm_success));
            orderRecordsModel.setMoneyConfirmStatus(1);
            adapter.notifyItemChanged(mPosition, 1);
        });

        viewModel.onDelayClick(binding.includeSelect.tvSignPerson, o -> {
            chooseNode = null;
            isSignPerson = true;
            treeDialog.reset();
            treeDialog.setFlag(0);
            treeDialog.setTitle(getString(R.string.please_choose_sign_person));
            treeDialog.showDialog();
        });

        viewModel.onDelayClick(binding.includeSelect.ivDelete, o -> {
            chooseNode = null;
            orderListParamsModel.setUserId(null);
            binding.includeSelect.tvSignPerson.setText("");
            binding.includeSelect.tvSignPerson.setEnabled(true);
            binding.includeSelect.ivDelete.setVisibility(View.GONE);
            treeDialog.reset();
        });

        viewModel.onDelayClick(binding.includeSelect.tvServicePerson, o -> {
            chooseNode = null;
            isSignPerson = false;
            treeDialog.reset();
            treeDialog.setFlag(1);
            treeDialog.setTitle(getString(R.string.please_choose_service_person));
            treeDialog.showDialog();
        });

        viewModel.onDelayClick(binding.includeSelect.ivDelete2, o -> {
            chooseNode = null;
            orderListParamsModel.setPromotionId(null);
            binding.includeSelect.tvServicePerson.setText("");
            binding.includeSelect.tvServicePerson.setEnabled(true);
            binding.includeSelect.ivDelete2.setVisibility(View.GONE);
            treeDialog.reset();
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getOrderList(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getOrderList(page);
            }
        });

        viewModel.onDelayClick(binding.includeTop.ivSelect, o -> binding.drawerLayout.openDrawer(GravityCompat.END));
        viewModel.onDelayClick(binding.includeTop.ivSearch, o -> JumpIntent.jump(this, SearchOrderActivity.class));
        viewModel.onDelayClick(binding.includeSelect.tvStartDate, o -> {
            isStart = true;
            timePicker.showPickerView();
        });
        viewModel.onDelayClick(binding.includeSelect.tvEndDate, o -> {
            isStart = false;
            timePicker.showPickerView();
        });
        viewModel.onDelayClick(binding.includeSelect.tvConfirm, o -> {
            if (!TextUtils.isEmpty(binding.includeSelect.tvStartDate.getText().toString()) && TextUtils.isEmpty(binding.includeSelect.tvEndDate.getText().toString())) {
                ToastHelper.show(getString(R.string.please_choose_end_time));
                return;
            }
            if (!TextUtils.isEmpty(binding.includeSelect.tvEndDate.getText().toString()) && TextUtils.isEmpty(binding.includeSelect.tvStartDate.getText().toString())) {
                ToastHelper.show(getString(R.string.please_choose_start_time));
                return;
            }
            page = 1;
            binding.smartRefreshLayout.autoRefresh();
            binding.recyclerView.scrollToPosition(0);
            binding.drawerLayout.closeDrawers();
        });
        viewModel.onDelayClick(binding.includeSelect.tvReset, o -> {
            orderText = getString(R.string.all_order_text);
            orderStatusAdapter.resetData(1);
            orderTypeAdapter.resetData(2);
            paymentAdapter.resetData(3);
            workTypeAdapter.resetData(4);
            orderListParamsModel.setOrderStatus(null);
            orderListParamsModel.setType(null);
            orderListParamsModel.setRenewalState(null);
            orderListParamsModel.setMoneyConfirmStatus(null);
            orderListParamsModel.setServiceCategory(null);
            binding.includeSelect.tvStartDate.setText("");
            binding.includeSelect.tvEndDate.setText("");
            orderListParamsModel.setStartTime(null);
            orderListParamsModel.setEndTime(null);
            orderListParamsModel.setUserId(null);
            orderListParamsModel.setIsDept(null);
            orderListParamsModel.setPromotionId(null);
            binding.includeSelect.tvSignPerson.setText("");
            binding.includeSelect.tvSignPerson.setEnabled(true);
            binding.includeSelect.ivDelete.setVisibility(View.GONE);
            binding.includeSelect.tvServicePerson.setText("");
            binding.includeSelect.tvServicePerson.setEnabled(true);
            binding.includeSelect.ivDelete2.setVisibility(View.GONE);
            chooseNode = null;
            page = 1;
            binding.smartRefreshLayout.autoRefresh();
            binding.drawerLayout.closeDrawers();
        });

        adapter.addOnItemChildClickListener(R.id.ll_call, (baseQuickAdapter, view, i) -> {
            flag = 0;
            OrderListDataModel.OrderRecordsModel orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                mTelNumber = orderRecordsModel.getPhone();
                businessId = orderRecordsModel.getBusinessId();
                clientName = orderRecordsModel.getUsername();
                myDialog.setIconVisibility(View.GONE);
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, false);
            }
        });
        adapter.addOnItemChildClickListener(R.id.tv_phone, (baseQuickAdapter, view, i) -> {
            flag = 0;
            OrderListDataModel.OrderRecordsModel orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                mTelNumber = orderRecordsModel.getPhone();
                businessId = orderRecordsModel.getBusinessId();
                clientName = orderRecordsModel.getUsername();
                myDialog.setIconVisibility(View.GONE);
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, false);
            }
        });
        adapter.addOnItemChildClickListener(R.id.ll_payment_confirm, (baseQuickAdapter, view, i) -> {
            flag = 1;
            mPosition = i;
            orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                double price = orderRecordsModel.getPrice();
                double payedPrice = orderRecordsModel.getPayedPrice();
                orderId = orderRecordsModel.getId();
                if (payedPrice < price) {
                    ToastHelper.show(getString(R.string.unable_payment_confirm));
                } else {
                    myDialog.setText(context.getString(R.string.order_finish_pay_confirm), context.getString(R.string.order_payment_confirm_tips), context.getString(R.string.cancel), context.getString(R.string.confirm));
                    myDialog.setIconVisibility(View.VISIBLE);
                    myDialog.showDialog();
                }
            }
        });

        adapter.addOnItemChildClickListener(R.id.ll_add_follow, (baseQuickAdapter, view, i) -> {
            flag = 0;
            OrderListDataModel.OrderRecordsModel orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.orderIdKey, orderRecordsModel.getId());
                bundle.putString(Constant.orderNoKey, orderRecordsModel.getOrderNo());
                JumpIntent.jump(OrderListActivity.this, OrderAddFollowActivity.class, bundle);
            }
        });

        adapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            orderRecordsModel = baseQuickAdapter.getItem(i);
            mPosition = i;
            Bundle bundle = new Bundle();
            bundle.putString(Constant.idKey, orderRecordsModel.getId());
            JumpIntent.jump(this, OrderDetailsActivity.class, bundle);
        });

        adapter.addOnItemChildClickListener(R.id.tv_company_name, (baseQuickAdapter, view, i) -> {
            orderRecordsModel = baseQuickAdapter.getItem(i);
            if (orderRecordsModel != null) {
                if (orderRecordsModel.getEnterConfirmState() == 1) {
                    if (CommonUtil.isCanClick()) {
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.creditNoKey, orderRecordsModel.getCreditNo());
                        JumpIntent.jump(this, CompanyDetailsActivity.class, bundle);
                    }
                } else {
                    mPosition = i;
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.idKey, orderRecordsModel.getId());
                    JumpIntent.jump(this, OrderDetailsActivity.class, bundle);
                }
            }
        });
    }

    private void initSelectData() {
        // 订单状态 空全部、-1已删除、0预订单、1服务中、2服务完成、3已关闭
        orderStatusData.add(new LabelModel(getString(R.string.all), true));
        orderStatusData.add(new LabelModel(getString(R.string.yu_order_text), 0, false));
        orderStatusData.add(new LabelModel(getString(R.string.serving), 1, false));
        orderStatusData.add(new LabelModel(getString(R.string.service_finish), 2, false));
        orderStatusData.add(new LabelModel(getString(R.string.closed), 3, false));
        orderStatusData.add(new LabelModel(getString(R.string.already_delete), -1, false));
        orderStatusAdapter = new OrderLabelAdapter(context, orderStatusData, 1, this);
        binding.includeSelect.recyclerViewOrderStatus.setAdapter(orderStatusAdapter);
        orderStatusAdapter.submitList(orderStatusData);
        // 订单类型 0新签、1续费、2全部
        orderTypeData.add(new LabelModel(getString(R.string.all_data), 2, false));
        orderTypeData.add(new LabelModel(getString(R.string.new_sign), 0, false));
        orderTypeData.add(new LabelModel(getString(R.string.renew), 1, false));
        orderTypeAdapter = new OrderLabelAdapter(context, orderTypeData, 2, this);
        binding.includeSelect.recyclerViewOrderType.setAdapter(orderTypeAdapter);
        orderTypeAdapter.submitList(orderTypeData);
        // 款项完结 0未确认、1已确认
        paymentData.add(new LabelModel(getString(R.string.no_confirm), 0, false));
        paymentData.add(new LabelModel(getString(R.string.already_confirm), 1, false));
        paymentAdapter = new OrderLabelAdapter(context, paymentData, 3, this);
        binding.includeSelect.recyclerViewPayment.setAdapter(paymentAdapter);
        paymentAdapter.submitList(paymentData);
        // 业务类型 1企业、2个人
        workTypeData.add(new LabelModel(getString(R.string.company_work), 1, false));
        workTypeData.add(new LabelModel(getString(R.string.personal_work), 2, false));
        workTypeAdapter = new OrderLabelAdapter(context, workTypeData, 4, this);
        binding.includeSelect.recyclerViewWorkType.setAdapter(workTypeAdapter);
        workTypeAdapter.submitList(workTypeData);
    }

    @Override
    public void onLabelItemClickListener(int flag, LabelModel model) {
        switch (flag) {
            case 1:
                orderText = model.getRemark();
                orderListParamsModel.setOrderStatus(model.isSelect() ? model.getNum() : null);
                orderListParamsModel.setType(model.getNum() != null ? model.getNum() == 0 ? 2 : null : null);
                break;
            case 2:
                orderListParamsModel.setRenewalState(model.isSelect() ? model.getNum() : null);
                break;
            case 3:
                orderListParamsModel.setMoneyConfirmStatus(model.isSelect() ? model.getNum() : null);
                break;
            case 4:
                orderListParamsModel.setServiceCategory(model.isSelect() ? model.getNum() : null);
                break;
        }
    }

    private void initDialog() {
        timePicker = new TimePicker(this, true) {
            @Override
            public void confirm(String date) {
                if (isStart) {
                    if (!TextUtils.isEmpty(binding.includeSelect.tvEndDate.getText().toString())) {
                        if (DateUtil.getStringToDate(date) > DateUtil.getStringToDate(binding.includeSelect.tvEndDate.getText().toString())) {
                            ToastHelper.show(getString(R.string.time_hint1));
                            return;
                        }
                    }
                    binding.includeSelect.tvStartDate.setText(date);
                    orderListParamsModel.setStartTime(date + " 00:00:00");

                } else {
                    if (!TextUtils.isEmpty(binding.includeSelect.tvStartDate.getText().toString())) {
                        if (DateUtil.getStringToDate(binding.includeSelect.tvStartDate.getText().toString()) > DateUtil.getStringToDate(date)) {
                            ToastHelper.show(getString(R.string.time_hint2));
                            return;
                        }
                    }
                    binding.includeSelect.tvEndDate.setText(date);
                    orderListParamsModel.setEndTime(date + " 23:59:59");
                }
            }
        };

        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                if (flag == 0) {
                    RequestUtils.callNum(context, mTelNumber);
                    Constant.pushBusinessId = businessId;
                }
            }

            @Override
            public void rightClick() {
                if (flag == 0) {
                    RequestUtils.callbackOutbound(context, mTelNumber, businessId, clientName);
                } else {
                    showLoadingDialog();
                    viewModel.moneyConfirm(orderId);
                    orderId = null;
                }
            }
        };
    }

    private void initTreeDialog() {
        treeDialog = new TreeDialog(this, mTreeData) {

            @Override
            public void confirm(Node node) {
                chooseNode = node;
                if (isSignPerson) {
                    binding.includeSelect.tvSignPerson.setText(node.isChecked() ? node.getName() : "");
                    orderListParamsModel.setUserId(node.isChecked() ? node.getOrgId() : null);
                    orderListParamsModel.setIsDept(node.isChecked() ? node.getIsDept() == 1 ? 0 : null : null);
                    binding.includeSelect.tvSignPerson.setEnabled(!node.isChecked());
                    binding.includeSelect.ivDelete.setVisibility(node.isChecked() ? View.VISIBLE : View.GONE);
                } else {
                    binding.includeSelect.tvServicePerson.setText(node.isChecked() ? node.getName() : "");
                    orderListParamsModel.setPromotionId(node.isChecked() ? node.getOrgId() : null);
                    binding.includeSelect.tvServicePerson.setEnabled(!node.isChecked());
                    binding.includeSelect.ivDelete2.setVisibility(node.isChecked() ? View.VISIBLE : View.GONE);
                }
            }

            @Override
            public void search(String keyword, Node node) {
                showLoadingDialog();
                mKeyword = keyword;
                viewModel.getTreeList(keyword);
            }
        };
    }

    private void initList(List<Node> list) {
        if (list == null || list.size() == 0) return;
        for (int i = 0; i < list.size(); i++) {
            Node node = list.get(i);
            mTreeData.add(new Node(node.getName(), node.getId(), node.getParentId(), node.getIsDept(), node.getFullId(), node.getJobNumber(), node.getOrgId()));
            if (node.getChildren() == null || node.getChildren().size() == 0) {
                initList(node.getUserList());
            } else {
                initList(node.getChildren());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshOrderList)) {
                orderRecordsModel.setMoneyConfirmStatus(1);
                adapter.notifyItemChanged(mPosition, "1");
            }
        }
    }
}